<template>
  <div class="container">
    <!-- 白色卡片 -->
    <el-card>
      <!-- logo -->
      <img class="logo" src="../../assets/logo.png" alt="">
      <!-- 表单 -->
      <el-form ref="form" status-icon :model="form" :rules="rules">
        <el-form-item prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox :value="true">我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login()">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import auth from '@/utils/auth'
export default {
  name: 'LoginPage',
  data () {
    // 校验手机号函数
    const checkMobile = (rule, value, callback) => {
      // 对value进行校验，此时的value就是form.mobile
      if (/^1[3-9]\d{9}$/.test(value)) {
        // 通过
        callback()
      } else {
        callback(new Error('手机号格式不对'))
      }
    }
    return {
      // 表单数据对象
      form: {
        mobile: '13200000000',
        code: '246810'
      },
      // 表单校验规则对象
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码是6个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      // 通过el-form自己实例调用validate函数进行整体校验
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            // 进行登录请求
            const res = await this.$http.post('/v1_0/authorizations', this.form)
            console.log('请求结束')
            // 保存token到本地
            // localStorage.setItem('geek-client-pc-token', res.data.data.token)
            auth.setToken(res.data.data.token)
            // 跳转到首页
            this.$router.push('/')
          } catch (e) {
            this.$message.error(e.response.data.message || '登录失败')
          }
        }
      })
    }
  }
}
</script>
<style scoped lang="less">
.container {
  position: absolute;
  width: 100%;
  height: 100%;
  background: url(../../assets/login.png) no-repeat center / cover;
  // 饿了么的组件解析后，组件根标签回加载一个和组件名称一致的类名
  .el-card {
    width: 440px;
    height: 360px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }
    .el-form {
      padding: 0 20px;
      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
